package com.server.server_a10.mqttServer;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.server_a10.entity.Inform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class MqttController {
    @Resource
    private MqttGateway mqttGateway;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/send_mqtt")
    public Inform sendMqtt(@RequestBody MyMessage myMessage) throws JsonProcessingException {
        Inform inform = new Inform();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 发送消息到指定主题
            mqttGateway.sendToMqtt(myMessage.getTopic(), 1,objectMapper.writeValueAsString(myMessage.getContent()));
        }catch (Exception e){
            inform.setCode(500);
            inform.setData(e);
            inform.setMsg("请求失败");
            return inform;
        }
        inform.setMsg("success! send topic: " + myMessage.getTopic()+ ", message : " + myMessage.getContent());
        inform.setCode(200);

        return inform;
    }

    @PostMapping("/get_mqtt")
    public String getMqtt(@RequestBody Map<String, String> request){
        String topic = request.get("topic");
        return (String) redisTemplate.opsForValue().get(topic);
    }

    @PostMapping("/getMqttsByTopic")
    public Set<String> getMqttByTopic(@RequestBody Map<String, Object> request){
        String topic = (String) request.get("topic");
        Set<String> keys = redisTemplate.keys(topic + "*");
        return keys;
    }
}
